package com.xgkj.diyiketang.util.xiangce;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.activity.BaseActivity;
import com.xgkj.diyiketang.activity.MyPhotoActivity;
import com.xgkj.diyiketang.activity.UserInfoActivity;
import com.xgkj.diyiketang.util.PalLog;
import com.xgkj.diyiketang.weidget.NoScrollGridView;
import com.xgkj.diyiketang.R;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Collections;

public class PhoneMainActivity extends BaseActivity implements View.OnClickListener{
    private final String TAG = getClass().getSimpleName();
    private final int result_code = 100;
    private Context mContext;
    private TextView photoFolderBtn;
    private TextView nameTextView;
    private TextView cancelTextView;
    private NoScrollGridView mGridView;
    private TextView previewText;
    private Button sendBtn;
    private TextView back;

    private PhotoImageAdapter mAdapter;

    private ArrayList<PhotoFolderInfo> folderList;
    private static ArrayList<PhotoImageInfo> imageList = new ArrayList<PhotoImageInfo>();
    private PhotoHelper photoHelper;
    private Handler mHandler;
    private Handler myhandler;
    private boolean isMain;



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.phone_main);
        mContext = this;
        myhandler = getHandler();
        Intent intent = getIntent();
        String from = intent.getStringExtra(ProtocolConst.PHOTO_FROM);
        initView();
        isMain = true;
        if (TextUtils.isEmpty(from) || from.equals(ProtocolConst.FROM_MAIN)) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    getImageList();
                    Looper.prepare();
                    myhandler.sendEmptyMessage(1);
                    Looper.loop();
                }
            }).start();
        }else {
            isMain = false;
            photoFolderBtn.setVisibility(View.GONE);
            back.setVisibility(View.VISIBLE);
            imageList = (ArrayList<PhotoImageInfo>) intent.getSerializableExtra(ProtocolConst.IMAGE_LIST);
            Collections.sort(imageList);
            refreshData();
        }
    }



    private void initView(){
        photoFolderBtn = (TextView) findViewById(R.id.photofolder);
        photoFolderBtn.setOnClickListener(this);
        photoFolderBtn.setVisibility(View.VISIBLE);
        back = (TextView)findViewById(R.id.back);
        back.setOnClickListener(this);
        back.setVisibility(View.GONE);
        nameTextView = (TextView) findViewById(R.id.phoneName);
        cancelTextView = (TextView) findViewById(R.id.cancel_btn);
        cancelTextView.setOnClickListener(this);
        mGridView = (NoScrollGridView) findViewById(R.id.photolist);
        previewText = (TextView) findViewById(R.id.preview);
        previewText.setOnClickListener(this);
        sendBtn = (Button) findViewById(R.id.sendphoto);
        sendBtn.setOnClickListener(this);
        mAdapter = new PhotoImageAdapter(mContext,mGridView);
        mGridView.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(new PhotoImageAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(CheckBox view, int position, boolean isChecked, ImageView chooseBt) {
//                PalLog.e(TAG,"######"+position+"####"+isChecked);
                if (PhotoConstant.selectImageList.size() >= PhotoConstant.num) {
                    view.setChecked(false);
                    chooseBt.setVisibility(View.GONE);
                    if (!removeOneData((PhotoImageInfo) mAdapter.getItem(position))) {
//                        PalLog.e(TAG,"111111");
                        Toast.makeText(mContext, getString(R.string.only_select_nine),
                                Toast.LENGTH_SHORT).show();
                    }
                    return;
                }
                if (isChecked) {
                    chooseBt.setVisibility(View.VISIBLE);
                    PhotoImageInfo imageInfo = (PhotoImageInfo) mAdapter.getItem(position);
                    if (!isContains(imageInfo)) {
                        PhotoConstant.selectImageList.add(imageInfo);
                    }
//                    sendBtn.setText(String.format(getString(R.string.send_photo_num),PhotoConstant.selectImageList.size()));
                } else {
//                    PhotoConstant.selectImageList.remove((PhotoImageInfo) mAdapter.getItem(position));
                    removeOneData((PhotoImageInfo) mAdapter.getItem(position));
                    chooseBt.setVisibility(View.GONE);
//                    sendBtn.setText(String.format(getString(R.string.send_photo_num),PhotoConstant.selectImageList.size()));
                }

                isShowOkBt();
            }
        });
    }

    private void getImageList(){
        photoHelper = PhotoHelper.getHelper();
        photoHelper.init(mContext);
        folderList = (ArrayList<PhotoFolderInfo>) photoHelper.getImagesBucketList(true);
        Collections.sort(folderList);
        imageList.clear();
        for (int i=0;i<folderList.size();i++){
//            PalLog.e(TAG,"文件夹名称:"+folderList.get(i).folderName);
            imageList.addAll(folderList.get(i).imageList);
        }

        Collections.sort(imageList);
    }

    private boolean removeOneData(PhotoImageInfo imageItem) {
        for (int i=0;i<PhotoConstant.selectImageList.size();i++){
            PhotoImageInfo info = PhotoConstant.selectImageList.get(i);
            if (info.imageId == imageItem.imageId){
                PhotoConstant.selectImageList.remove(info);
                sendBtn.setText(String.format(getString(R.string.send_photo_num),PhotoConstant.selectImageList.size()));
                return true;
            }
        }
//        if (PhotoConstant.selectImageList.contains(imageItem)) {
//            PhotoConstant.selectImageList.remove(imageItem);
//            sendBtn.setText(String.format(getString(R.string.send_photo_num),PhotoConstant.selectImageList.size()));
//            return true;
//        }
        return false;
    }

    @Override
    protected void onResume() {
        super.onResume();
        isShowOkBt();
    }

    public void isShowOkBt() {
        if (PhotoConstant.selectImageList.size() > 0) {
            sendBtn.setText(String.format(getString(R.string.send_photo_num),PhotoConstant.selectImageList.size()));
            sendBtn.setEnabled(true);
            previewText.setClickable(true);
            previewText.setTextColor(getResources().getColor(R.color.video_fenlei_font));
        } else {
            sendBtn.setText(String.format(getString(R.string.send_photo_num),PhotoConstant.selectImageList.size()));
            sendBtn.setEnabled(false);
            previewText.setClickable(false);
            previewText.setTextColor(getResources().getColor(R.color.hint_color));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.photofolder:
                Intent folderIntent = new Intent(mContext,PhoneFolderActivity.class);
                folderIntent.putParcelableArrayListExtra(ProtocolConst.FOLDER_LIST,folderList);
                startActivity(folderIntent);
                break;
            case R.id.cancel_btn:
                PhotoConstant.selectImageList.clear();
                Intent intent = new Intent(mContext, MyPhotoActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
                break;
            case R.id.preview:
                Intent bigIntent = new Intent(mContext,GalleryActivity.class);
                startActivity(bigIntent);
                break;
            case R.id.sendphoto:
                Intent okintent = new Intent(mContext, MyPhotoActivity.class);
                okintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(okintent);
                break;
            case R.id.back:
                finish();
                break;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(keyCode == KeyEvent.KEYCODE_BACK){
            if (isMain) {
                PhotoConstant.selectImageList.clear();
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    private void refreshData(){
        mAdapter.updateData(imageList,PhotoConstant.selectImageList);
        isShowOkBt();
    }

    private boolean isContains(PhotoImageInfo info){
        for (int i=0;i<PhotoConstant.selectImageList.size();i++){
            PhotoImageInfo selectInfo = PhotoConstant.selectImageList.get(i);
            if (selectInfo.imageId == info.imageId){
                return true;
            }
        }
        return false;
    }

    private Handler getHandler(){
        if (mHandler == null){
            mHandler = new PhotoHandler(PhoneMainActivity.this);
        }
        return mHandler;
    }

    static class PhotoHandler extends Handler{
        private WeakReference<PhoneMainActivity> mWeakReference;
        public PhotoHandler(PhoneMainActivity activity) {
            mWeakReference = new WeakReference<PhoneMainActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what ==1){
                mWeakReference.get().refreshData();
            }
        }
    }
}
